package daoImpl;

import java.awt.image.DirectColorModel;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

import constants.Constants;
import constants.Diretorios;



public class ConnectBD {

	private static Logger log = Logger.getLogger(ConnectBD.class);

	private final String DRIVER = "com.mysql.jdbc.Driver";
	private String URL = "jdbc:mysql://";
	private static ConnectBD instance;
	private String user;
	private String password;
	private String dataBase;


	private Connection connection;

	private ConnectBD() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {

		log.debug("Recuperando os dados da conexao com o banco!");
		Diretorios diretorios = Diretorios.getInstance();
		Properties properties = new Properties();
		properties.load(new FileInputStream(Constants.SISGEREMP_PROPERTIES_FILE));

		Class.forName(this.DRIVER);
		diretorios.setDirSisgecon(properties.getProperty("DIR_SISGEREMP"));
		diretorios.setDirMySQL(properties.getProperty("DIRETORIO_MYSQL"));
		diretorios.setDirDump(properties.getProperty("DIR_DUMP"));

		this.user = properties.getProperty("USER");
		this.password = properties.getProperty("SENHA");
		this.dataBase = properties.getProperty("DATABASE");

		this.URL += properties.getProperty("HOST") + "/"
		+ this.dataBase + "?user=" + this.user
		+ "&password=" + this.password;

		this.connection = getConnection();
	}

	/** Cria uma instancia para a classe
	 *
	 * @return
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 * @throws IOException
	 * @throws FileNotFoundException
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static ConnectBD getInstance() throws FileNotFoundException, IOException,
	ClassNotFoundException, SQLException {
		if (instance == null) {
			instance = new ConnectBD();
		}
		return instance;
	}

	/**
	 * @return the connection
	 * @throws SQLException
	 */
	public Connection getConnection() throws SQLException{
		if (this.connection == null) {
			this.connection = DriverManager.getConnection(this.URL);
		}
		return this.connection;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getDataBase() {
		return dataBase;
	}

	public void setDataBase(String dataBase) {
		this.dataBase = dataBase;
	}
}